import requests
import time
import json
import os
import hashlib

# 输入关键字
def keyword():
	word = input("请输入要下载的图片关键词\n")
	if len(word.strip()) == 0 :
		return keyword()
	else :	
		return word	

# 关键字
word = keyword()

# 请求头
header = {
	"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36"
}

# 创建目录
download_path = word
if not os.path.isdir(download_path) :
	os.mkdir(download_path, 755)

# 开始时间
start_time = time.time()
start_htime = int(round(start_time * 1000))

# 下载数量
num = 0
# 百度分页
page = 0
# 是否还有图片
end = True
while end :	

	page = page + 30
	t = time.time()
	htime = int(round(t * 1000))
	url = 'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=10162529206245148470&ipn=rj&ct=201326592&is=&fp=result&fr=&word='+str(word)+'&queryWord=php&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&s=&se=&tab=&width=&height=&face=0&istype=2&qc=&nc=1&expermode=&nojc=&isAsync=&pn='+str(page)+'&rn=30&gsm=1e&'+str(htime)+'='

	# 发起请求
	resData = requests.get(url,headers=header)

	# 请求成功
	if resData.status_code == 200 :
		# 把返回的json数据解析成数组
		try :
			resArr = json.loads(resData.text)
		except ValueError :
			continue

		# 本页返回的图片数据大于0条
		if len(resArr['data'][0]) > 0 :
			# 循环图片数据
			for val in resArr['data'] :
				# 数组是否存在thumbURL下标数据(图片url)	
				if 'thumbURL' in val :
					# 获取图片
					r = requests.get(val['thumbURL'], headers=header)
					# 文件名
					sha1 = hashlib.sha1() 
					sha1.update(val['thumbURL'].encode('utf-8')) 
					file_name = sha1.hexdigest()
					# 文件路径
					file_path = download_path + "/" + file_name +".jpeg"
					# 下载图片
					with open(file_path , 'wb') as f :
						size = f.write(r.content)
						if size > 0 :
							num = num + 1
							print("下载成功"+str(num)+" : " + val['thumbURL'])	
						f.close()
				else :
					# 本页没有图片数据了
					continue		
		else :
			# 已经没有数据了
			end = False				
	else :
		# 请求失败的状态码
		print(resData.status_code)

else :
	# 结束时间
	end_time = time.time()
	end_htime = int(round(end_time * 1000))
	use_time = end_htime - start_htime
	# 下载结束
	print(str(word)+"下载结束,共"+str(num)+"张图片,耗时"+str(use_time)+"ms")
	